// content-script.js

import { simplifyHTML, estimateTokenCount, unwrapSingleParentImgs } from "../assets/waws.js"; 
import { Readability } from "@mozilla/readability";

let timerId = null;
const API_URL1 = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
const API_KEY1 = "sk-5ec20074966244e1802321f3de770b97";
const platformModel = {
    "qwen-plus": {
        value: "qwen-plus",
        url: API_URL1,
        key: API_KEY1,
    },
    "deepseek-v3": {
        value: "deepseek-v3",
        url: API_URL1,
        key: API_KEY1,
    },
    "qwen-turbo": {
        value: "qwen-turbo",
        url: API_URL1,
        key: API_KEY1,
    },
    "qwen-max-2025-01-25": {
        value: "qwen-max-2025-01-25",
        url: API_URL1,
        key: API_KEY1,
    },
    "qwen-plus-2025-01-25": {
        value: "qwen-plus-2025-01-25",
        url: API_URL1,
        key: API_KEY1,
    },
    "gm": {
        value: "gm",
        url: "https://ai.never-down.cn/gm/generate-content",
        key: 'FUJ1rnw*yqm_uwe2euk',
    },
    "doubao-1-5-pro-32k-250115": {
        value: "doubao-1-5-pro-32k-250115",
        url: "https://ark.cn-beijing.volces.com/api/v3/chat/completions",
        key: '5014a8ef-c7d5-4eef-90aa-873debe58286',
    },
    "doubao-1-5-pro-256k-250115": {
        value: "doubao-1-5-pro-256k-250115",
        url: "https://ark.cn-beijing.volces.com/api/v3/chat/completions",
        key: '5014a8ef-c7d5-4eef-90aa-873debe58286',
    }
    
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    sendResponse({ data: "来自background的数据" });
    if (request.action === "trans") {
        // console.log(request);
        tip("提取成功")
        unwrapSingleParentImgs();
        var documentClone = document.cloneNode(true);
        var article = new Readability(documentClone).parse();
        const dialog = document.createElement('div');
        let dialogHtml = `
        <div class="chrome-trans-dialog1">
            <div class="chrome-trans-dialog1-cover"></div>
            <div class="chrome-trans-dialog1-content">
                <div class="chrome-trans-dialog1-item chrome-trans-dialog1-left">
                    <textarea class="chrome-trans-dialog1-desc" placeholder="请输入提示词">请帮我把这篇文章翻译成英文，只翻译文本内容，并保留html标签</textarea>
                    <textarea class="chrome-trans-dialog1-htmlText"></textarea>
                    <p>输入token数：<span class="chrome-trans-dialog1-htmlText-length"></span></p>
                </div>
                <div class="chrome-trans-dialog1-item chrome-trans-dialog1-right">
                    <select class="chrome-trans-dialog1-select" value="qwen-plus">
                    `
                    for(let key in platformModel){
                        dialogHtml += `<option value="${key}">${platformModel[key].value}</option>`
                    }
                    dialogHtml += `
                    </select>
                    <button class="chrome-trans-dialog1-goTrans">去翻译</button>
                    <p class="chrome-trans-dialog1-goTrans-time"><span class="chrome-trans-dialog1-goTrans-time-text"></span><span class="chrome-trans-dialog1-goTrans-time-span"></span></p>
                    <textarea class="chrome-trans-dialog1-resHtml"></textarea>
                    <p>返回token数：<span class="chrome-trans-dialog1-restoken-length"></span></p>
                </div>
            </div>
        </div>
        `;
        dialog.innerHTML = dialogHtml;
        document.body.appendChild(dialog);
        let simplifyData = simplifyHTML(article.content);
        console.log("simplifyData.length:",simplifyData.length);
        let tokenCount = estimateTokenCount(simplifyData);
        console.log("tokenCount:",tokenCount);
        document.querySelector(".chrome-trans-dialog1-htmlText-length").textContent = tokenCount;

        document.querySelector(".chrome-trans-dialog1-htmlText").value = simplifyData;
        addEventHandle(dialog);
    }else if (request.action === "responseData") {
        let completion = request?.data;
        console.log("responseData:",completion);
        let transHtml = '';
        if(completion?.status !== 200){
            transHtml = completion?.message;
        }else{
            if(completion?.data?.choices && completion?.data?.choices.length > 0){
                transHtml = completion?.data?.choices[0]?.message?.content;
            }else{
                transHtml = completion?.data?.content;
            }
        }
        let completion_tokens = completion?.data?.usage?.completion_tokens || 0;
        transEnd();
        document.querySelector(".chrome-trans-dialog1-resHtml").textContent = transHtml;
        document.querySelector(".chrome-trans-dialog1-restoken-length").textContent = completion_tokens;
    }
});

function addEventHandle(dialog){
    document.querySelector(".chrome-trans-dialog1-goTrans").addEventListener('click',async (event) => {
        const that = event.target;
        try {
            let textAreaDesc = document.querySelector(".chrome-trans-dialog1-desc").value;
            let model = document.querySelector(".chrome-trans-dialog1-select").value;
            if(!textAreaDesc){
                return tip("请输入提示词");
            }
            
            timerId = null;
            transStart(that)
            let textAreaContent = document.querySelector(".chrome-trans-dialog1-htmlText").value;
            // 请求
            let modelObj = {
                value: model,
                url: platformModel[model].url,
                key: platformModel[model].key
            }
            sendConfigBg(textAreaContent,textAreaDesc,modelObj);
                        

        } catch (error) {
            document.querySelector(".chrome-trans-dialog1-resHtml").textContent = error?.response?.data?.message;
            console.log("error1:",error);
            
        }
    });

    document.querySelector(".chrome-trans-dialog1-htmlText").addEventListener('input',async (event) => {
        let textAreaContent = event.target.value;
        let tokenCount = estimateTokenCount(textAreaContent);
        document.querySelector(".chrome-trans-dialog1-htmlText-length").textContent = tokenCount;
    });
}

let startTime = Date.now(); // 记录开始时间
let isFinished = false; // 标记是否完成
function updateTimerDisplay() {
    if (!isFinished) {
        const elapsedMilliseconds = Date.now() - startTime;
        const seconds = (elapsedMilliseconds / 1000).toFixed(2);
        document.querySelector(".chrome-trans-dialog1-goTrans-time-span").textContent = `${seconds}s`;
    }
}
function transStart(that) {
    document.querySelector(".chrome-trans-dialog1-goTrans-time-text").textContent = `正在生成: `;
    document.querySelector(".chrome-trans-dialog1-resHtml").textContent = "";
    startTime = Date.now();
    isFinished = false;
    that.disabled = true;
    timerId = setInterval(updateTimerDisplay, 100);

}
function transEnd() {
    clearInterval(timerId); // 清理计时器
    console.log("计时完成！");
    isFinished = true;
    document.querySelector(".chrome-trans-dialog1-goTrans").disabled = false;
    document.querySelector(".chrome-trans-dialog1-goTrans-time-text").textContent = `耗时: `;
    document.querySelector(".chrome-trans-dialog1-cover").addEventListener('click', () => {
        let dialog = document.querySelector(".chrome-trans-dialog1");
        dialog?.remove();
    });
}


function sendConfigBg(htmlStr,desc,modelObj) {
    console.log(modelObj);
    let data = {};
    if(modelObj.value == "gm"){
        data = {
            system: desc,
            text: htmlStr
        };
    }else{
        data = {
            "messages": [
                { 
                    role: "system", 
                    content: desc
                },
                {
                    role: "user",
                    content: htmlStr
                }
            ],
            "model": modelObj.value,
            "max_tokens": 8192
        };
    }
    
    let config = {
        method: 'post',
        url: modelObj.url,
        headers: { 
            'Content-Type': 'application/json', 
            'Accept': '*/*', 
            'Authorization': `Bearer ${modelObj.key}`,
        },
        timeout: 1000000,
        maxBodyLength: Infinity,
        maxContentLength: Infinity,
        data : JSON.stringify(data)
    };
    chrome.runtime.sendMessage({action: "axios", config: config}, function(response) {
        // console.log("收到回复：" + response);
    });
}



// 简单的消息通知
var tipCount = 0;
function tip(info) {
    info = info || "";
    var ele = document.createElement("div");
    ele.className = "chrome-plugin-simple-tip slideInLeft";
    ele.style.top = tipCount * 70 + 20 + "px";
    ele.innerHTML = `<div>${info}</div>`;
    document.body.appendChild(ele);
    ele.classList.add("animated");
    tipCount++;
    setTimeout(() => {
        ele.style.top = "-100px";
        setTimeout(() => {
            ele.remove();
            tipCount--;
        }, 400);
    }, 3000);
}
